from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework_jwt.settings import api_settings

from oauth.models import OAuthQQUser
from users.models import User
from itsdangerous import TimedJSONWebSignatureSerializer as TJS
from django.conf import settings


class OAuthQQSerializer(serializers.Serializer):
    """QQ登录绑定的序列化器"""
    mobile = serializers.RegexField(max_length=11, regex='^1[3-9]\d{9}$')
    sms_code = serializers.CharField(max_length=6, min_length=6, write_only=True)
    password = serializers.CharField(max_length=20, min_length=6, write_only=True)
    access_token = serializers.CharField(write_only=True)

    def validate(self, attrs):
        """校验数据, 然后把校验后的返回的对象返回, 传递给下面的创建或者更新函数"""

        # 短信验证码验证 短信验证码并没有存储在表格里面
        mobile = attrs['mobile']
        # 获取短信验证码 是先创建数据库链接对象 然后再去获取的
        redis_conn = get_redis_connection('verify')
        real_sms_code = redis_conn.get('sms_code_%s' % mobile).decode()
        sms_code = attrs['sms_code']
        if real_sms_code != sms_code:
            raise serializers.ValidationError('短信验证码错误')
        tjs = TJS(settings.SECRET_KEY, 300)

        data = attrs['access_token']
        try:
            # access——token解密验证

            openid_data = tjs.loads(data)

        except Exception:
            raise serializers.ValidationError('错误的access_token值')
        openid = openid_data['openid']

        if not openid:
            raise serializers.ValidationError('openid无效')
        # 用户验证
        # 1、用户查询不到
            # 创建用户
        user = None
        try:
            user = User.objects.get(mobile=mobile)
            if not user.check_password(attrs['password']):
                raise serializers.ValidationError('密码错误')
        except Exception:
            pass

        attrs['user'] = user
        attrs['openid'] = openid
        return attrs

        # 用户查询到  校验密码

    def create(self, validated_data):


        # 绑定操作  创建出OAuthQQModel模型类对象
        user = validated_data['user']
        # use r = User.objects.get(mobile=validated_data['mobile'])

        if not user:
            user = User.objects.create_user(
                username=validated_data['mobile'],
                password=validated_data['password'],
                mobile=validated_data['mobile'],
            )
            # 将用户绑定openid
        OAuthQQUser.objects.create(
            openid=validated_data['openid'],
            user=user
        )

        return user




